from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from datetime import datetime
from typing import List
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import auth
import database
import schemas
from routers.auth import get_db, get_current_user

router = APIRouter()

@router.post("/record", response_model=schemas.DataProcessingRecordResponse)
async def create_processing_record(
    record_data: schemas.DataProcessingRecordBase,
    current_user: database.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """记录数据处理操作"""
    # 使用auth模块中的记录函数
    record = auth.record_data_processing(
        db=db,
        user_id=current_user.id,
        operation_type=record_data.operation_type,
        operation_details=record_data.operation_details,
        file_name=record_data.file_name,
        duration_ms=record_data.duration_ms,
        status=record_data.status,
        error_message=record_data.error_message
    )
    
    # 返回记录信息（包含用户名）
    return schemas.DataProcessingRecordResponse(
        id=record.id,
        user_id=record.user_id,
        username=current_user.username,
        operation_type=record.operation_type,
        operation_details=record.operation_details,
        file_name=record.file_name,
        processing_time=record.processing_time,
        duration_ms=record.duration_ms,
        status=record.status,
        error_message=record.error_message
    )

@router.get("/my-records", response_model=List[schemas.DataProcessingRecordResponse])
async def get_my_processing_records(
    limit: int = 50,
    current_user: database.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的数据处理记录"""
    records = db.query(database.DataProcessingRecord).filter(
        database.DataProcessingRecord.user_id == current_user.id
    ).order_by(database.DataProcessingRecord.processing_time.desc()).limit(limit).all()
    
    # 格式化响应
    response_records = []
    for record in records:
        response_records.append(schemas.DataProcessingRecordResponse(
            id=record.id,
            user_id=record.user_id,
            username=current_user.username,
            operation_type=record.operation_type,
            operation_details=record.operation_details,
            file_name=record.file_name,
            processing_time=record.processing_time,
            duration_ms=record.duration_ms,
            status=record.status,
            error_message=record.error_message
        ))
    
    return response_records

@router.get("/operation-types")
async def get_operation_types(
    current_user: database.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取操作类型列表"""
    # 从数据库中获取已存在的操作类型
    operation_types = db.query(database.DataProcessingRecord.operation_type).distinct().all()
    
    # 定义常见的操作类型
    common_types = [
        "image_upload",
        "dicom_process", 
        "tdc_analysis",
        "vessel_extraction",
        "cbf_calculation",
        "cbv_calculation",
        "mtt_calculation",
        "ttp_calculation",
        "image_windowing",
        "image_zoom",
        "image_pan",
        "marker_annotation",
        "data_export",
        "file_download"
    ]
    
    # 合并已存在的和常见的操作类型
    all_types = set(common_types)
    for type_tuple in operation_types:
        if type_tuple[0]:
            all_types.add(type_tuple[0])
    
    return {
        "operation_types": sorted(list(all_types))
    } 